<?php

namespace app\models;

/**
 * 权限处理模型
 * 
 * @author liaojianwen
 *         @date 2017-01-07
 */
use app\enum\EnumOther;
use app\models\BaseModel;
use Yii;
use app\dao\AuthItemDAO;
use app\enum\RoleEnum;

class PermissionModel extends BaseModel
{
	/**
	 * 实例化对象
	 * 
	 * @author liaojianwen
	 *         @date 2017-01-07
	 * @return PermissionModel
	 */
	public static function model($className = __CLASS__)
	{
		return parent::model ( $className );
	}
	
	/**
	 * 保存分组
	 * 
	 * @author liaojianwen
	 *         @date 2017-01-07
	 */
	public function saveGroup($name, $group)
	{
		if (empty ( $name )) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'group name is empty' );
		}
		$auth = Yii::$app->authManager;
		if ($group) {
			// 编辑
			$changRole = $auth->getRole ( $group );
			$changRole->description = $name;
			$res = $auth->update ( $group, $changRole );
			if (! $res) {
				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save group failure' );
			}
			return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, '' );
		}
		$groupName = EnumOther::PRE_GROUP . $name;
		$role = $auth->createRole ( $groupName );
		$role->description = $name;
		$result = $auth->add ( $role );
		
		if (! $result) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save group failure' );
		}
		return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, '' );
	}
	
	/**
	 * 获取分组列表
	 * 
	 * @param $cond 查询条件        	
	 * @param [] $pageInfo
	 *        	页面信息
	 * @author liaojianwen
	 *         @date 2017-01-07
	 */
	public function getGroups($cond, $pageInfo)
	{
		$result = AuthItemDAO::getInstance ()->getGroups ( $cond, $pageInfo );
		if (! $result) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'no data found' );
		}
		return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, $result );
	}
	
	/**
	 * 根据group_name 获取权限
	 * 
	 * @author liaojianwen
	 *         @date 2017-01-10
	 */
	public function listAuth($gname)
	{
		if (empty ( $gname )) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'group name is empty' );
		}
		$auth = Yii::$app->authManager;
		$allRoles = $auth->getPermissions ();
		if (! $allRoles) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'no data found' );
		}
		$allRoles = json_decode ( json_encode ( $allRoles ), true );
		$result = [ ];
		$res = [ ];
		foreach ( $allRoles as $auth ) {
			$RouterPos = strpos ( $auth ['name'], '/' );
			$_router = substr ( $auth ['name'], 0, $RouterPos );
			$_GROUP = RoleEnum::$group;
			$group_name = $_GROUP [$_router];
			array_key_exists ( $group_name, $res ) ? '' : $res [$group_name] = array ();
			array_push ( $res [$group_name], [ 
					'name' => $auth ['name'],
					'description' => $auth ['description'] 
			] );
		}
		
		$result ['auth'] = $res;
		$auths = Yii::$app->authManager;
		$groupRoles = $auths->getPermissionsByRole ( $gname );
		$groupRoles = json_decode ( json_encode ( $groupRoles ), true );
		
		$rest = [ ];
		foreach ( $groupRoles as $role ) {
			$RouterPos = strpos ( $role ['name'], '/' );
			$_router = substr ( $role ['name'], 0, $RouterPos );
			$_GROUP = RoleEnum::$group;
			$group_name = $_GROUP [$_router];
			array_key_exists ( $group_name, $rest ) ? '' : $rest [$group_name] = array ();
			array_push ( $rest [$group_name], [ 
					'name' => $role ['name'],
					'description' => $role ['description'] 
			] );
		}
		$result ['group'] = $rest;
		if (empty ( $result )) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'no data found' );
		}
		
		return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, $result );
	}
	
	/**
	 * 保存分组的权限
	 * 
	 * @param $group 分组名称        	
	 * @param $remove []
	 *        	删除的权限集合
	 * @param $permission []
	 *        	组的权限集合
	 * @author liaojianwen
	 *         @date 2017-01-11
	 */
	public function saveAuth($group, $remove, $permission)
	{
		try {
			if (empty ( $group ) || empty ( $permission )) {
				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'missing group name' );
			}
			$auth = Yii::$app->authManager;
			
			if (is_array ( $permission )) {
				foreach ( $permission as $mision ) {
					$oneRole = $auth->getRole ( $group );
					$onePermission = $auth->getPermission ( $mision );
					if ($auth->hasChild ( $oneRole, $onePermission )) {
						// 权限已在分组,继续操作
						continue;
					} else {
						$auth->addChild ( $oneRole, $onePermission );
					}
				}
			}
			
			if (is_array ( $remove )) {
				foreach ( $remove as $rem ) {
					$oneRole = $auth->getRole ( $group );
					$onePermission = $auth->getPermission ( $rem );
					if ($auth->hasChild ( $oneRole, $onePermission )) {
						$auth->removeChild ( $oneRole, $onePermission );
					}
				}
			}
			return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, '' );
		} catch ( \Exception $e ) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', '' );
		}
	}
	
	/**
	 * @desc删除分组
	 * @author liaojianwen
	 * @date 2017-01-12
	 */
	public function delGroup($names)
	{
		if (empty ( $names )) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
		}
		$tr = Yii::$app->db->beginTransaction ();
		try {
			$name = explode ( ',', $names );
			
			$auth = Yii::$app->authManager;
			foreach ( $name as $group ) {
				if($group == 'admin'){
					continue;
				}
				$oneRole = $auth->getRole($group);
				$res = $auth->remove($oneRole);
				if(!$res){
					$tr->rollBack();
					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'del failure');
				}
			}
			$tr->commit();
			return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
		} catch ( \Exception $e ) {
			$tr->rollBack ();
			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', $e->getMessage()); 
		}
	}
	
	/**
	 * @desc 获取权限分组
	 * @param $id user_id
	 * @author liaojianwen
	 * @date 2017-01-12
	 */
	public function getAuthRole($id)
	{
		$auths= Yii::$app->authManager;
		
		$roles = $auths->getRoles();
		$roles = json_decode(json_encode($roles),true);
		$auth = Yii::$app->authManager;
		$userRole = $auth->getRolesByUser($id);
		$userRole = json_decode(json_encode($userRole),true);
		$result =[];
		foreach ($roles as &$role){
			foreach ($userRole as $user){
				if($role['name'] == $user['name']){
					$role['checked'] = true;
				} 
			}
			array_push($result, $role);
		}
		if(empty($result)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'no data found');
		}
		return $this->handleApiFormat(EnumOther::ACK_SUCCESS, $result);
	}
}